package com.hcc.flow.server.dao.flowDesign;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.mapping.StatementType;

import com.hcc.flow.server.model.flowDesign.FlowDesignTemp;
import com.hcc.flow.server.vo.flowDesign.FlowDesignTempLogVO;
/**
 * FlowTempDao
 * @author admin
 *
 */
@Mapper
public interface FlowDesignTempDao {

    @Select("select * from flow_design_temp t where t.flow_temp_id = #{id}")
    FlowDesignTemp getById(String id);
    
    @Select("select t.flow_id,t.create_time,t.edit_log,t.version,u.USER_NAME create_user_name " 
    		+ "from flow_design_temp t " 
    		+ "LEFT JOIN flow_design t1 on t1.flow_id = t.flow_id " 
    		+ "LEFT JOIN sys_user u on t1.create_user_id=u.USER_ID "
    		+ "where t.flow_id = #{flowId} order by t.version desc")
	List<FlowDesignTempLogVO> getLogByFlowId(String flowId);

    @Delete("delete from flow_design_temp where flow_temp_id = #{id}")
    int delete(String id);

    int update(FlowDesignTemp flow);
    
    //@Options(useGeneratedKeys = true, keyProperty = "id")
    @SelectKey(statement="select replace(UUID(),'-','')", keyProperty="flowTempId", before=true, statementType=StatementType.STATEMENT,resultType=String.class)
    @Insert("insert into flow_design_temp(flow_temp_id,flow_id, flow_code, flow_name, flow_data,flow_remarks, create_time, create_user_id, is_used,edit_log,version) values(#{flowTempId}, #{flowId}, #{flowCode}, #{flowName},  #{flowData}, #{flowRemarks}, now(), #{createUserId}, #{isUsed},#{editLog},(select version from (select IFNULL(max(version)+1,1) version from flow_design_temp where flow_id = #{flowId}) sf))")
    int save(FlowDesignTemp flow);
	
	@Update("<script>"
    		+ "update flow_design_temp set is_used = #{status} where flow_temp_id in "
    		+ "<foreach item='item' index='index' collection='ids' open='(' separator=',' close=')'>"
            	+ "#{item}"
            + "</foreach>"
    		+ "</script>")
    int updateStatus(@Param("ids") List<String> ids,@Param("status") String status);
	
	@Select("select t.* from flow_design_temp t where t.flow_id = #{flowId} and t.flow_data is not null order by t.version desc limit 1")
	FlowDesignTemp getByFlowId(String flowId);
}
